##PBAR_ConvertHeaders.py
#
# convert the headersAll.txt file to comma separated file containing only import entries
# 4/1/2013, John Kwong
#
# 3/13/2014, JK, put code into main function

import numpy as np
import datetime, sys, time, csv

#script, fullFileName, fullFileNameWrite = argv

## open file for reading
#fullFileName = 'C:\Users\jkwong\Documents\Work\PBAR\data\headersAll.txt'
#fullFileName = r'C:\Users\jkwong\Documents\Work\HumanPortable\Data2\headersAll.txt'

##fullFileName = 'headersAll.txt'
    
def main(fullFilename, fullFileNameWrite):
    
    fid = open(fullFilename, 'r')
    
    # read in file
    txt = fid.read()
    txt = txt.split('\n')
    fid.close()
    
    ##go through and find the start location of entries
    starts = []
    datasetName = []
    for i in range(0,len(txt)):
        if len(txt[i]) > 0:
            if (txt[i][0] != ' ') and (not (txt[i][0].isdigit())) and (txt[i][0] != '-'):
                starts.append(i)
                datasetName.append(txt[i][0:4])
    # convert to np array
    starts = np.array(starts)
    acquisitionTime = []
    timeStamp = []
    header = []
    print i
    
    for i in range(0,len(starts)):
        # get acquisition time
        line = txt[starts[i]+6]
        t1 = line.find('=') + 1
        t2 = line.find('seconds')
        acquisitionTime.append(float(line[t1:t2]))
        # get the time stamp
        line = txt[starts[i]+7]
        t1 = line.find('=') + 6
        timeStamp.append(line[t1:])
        # get header
        header.append(txt[starts[i]+8][10:])
    # convert to epoch time
    timeNum = np.zeros(len(timeStamp))
    for ii in range(0,len(timeStamp)):
        timeNum[ii] = time.mktime(datetime.datetime.strptime(timeStamp[ii], '%b %d %H:%M:%S %Y').timetuple())
    
    timeOrderIndices = np.argsort(timeNum)
    acquisitionTime = np.array(acquisitionTime)
    datasetName = np.array(datasetName)
    timeStamp = np.array(timeStamp)
    timeNum = np.array(timeNum)
    header = np.array(header)
    
    # write to file
    #fullFileNameWrite = r'C:\Users\jkwong\Documents\Work\HumanPortable\Data2\datasetSummary.txt'
    #fullFileNameWrite = 'C:\Users\jkwong\Documents\Work\PBAR\data\datasetSummary.txt'
    #fullFileNameWrite = 'datasetSummary.txt'
    
    fid = open(fullFileNameWrite, 'wb');
    csvWriteObj = csv.writer(fid, delimiter = '\t')
    
    for j in range(0,len(header)):
        i = timeOrderIndices[j]
        csvWriteObj.writerow((datasetName[i], timeStamp[i], \
                              acquisitionTime[i], timeNum[i], header[i]))
        i += 1
    print i
    fid.close()
    
if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2])